<template>
    <div style="padding: 2%;">

        <a-card>
            <!-- 顶栏 -->
            <template #title>
                <div style="display: flex;align-items:center;">
                    <span style="font: 700 16px 微软雅黑">作者对应表</span>

                    <div style="flex-grow: 1;" />

                    <a-button type="primary" :icon="h(PlusOutlined)" @click="isInsert = true">新增数据</a-button>
                </div>

            </template>

            <!-- 查询表单 -->
            <a-form ref="formRef" name="advanced_search" style="margin: 0 0px 20px 10px;align-items: center;"
                :model="searchForm" layout="inline">


                <a-form-item name="cid" label="漫画ID">
                    <a-select v-model:value="searchForm.cid" placeholder="精确查询：漫画ID" style="width: 180px;"
                        :allowClear="true">
                        <a-select-option v-for="e in cartoon" :value="e.cid">
                            {{ e.cid + " : " + e.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item name="aid" label="作者ID">
                    <a-select v-model:value="searchForm.aid" placeholder="精确查询：作者ID" style="width: 180px;"
                        :allowClear="true">
                        <a-select-option v-for="e in authors" :value="e.aid">
                            {{ e.aid + " : " + e.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>


                <a-form-item class="m-left-auto">
                    <a-button type="primary" @click="getDataSource" :loading="loading">查询</a-button>
                    <a-button style="margin: 0 8px" @click="clearSearchForm">清空</a-button>
                </a-form-item>


            </a-form>

            <a-divider></a-divider>

            <!-- 数据表 -->
            <a-table :columns="columns" :data-source="dataSource" size="middle" :pagination="pagination" bordered>

                <template #bodyCell="{ column, text, record }">

                    <template v-if="column.dataType === 'date'">
                        {{ new Date(text).toLocaleString() }}
                    </template>

                    <template v-if="column.foreignKey">
                        {{ getToForeignKey(column.foreignKey, record) }}
                    </template>

                    <template v-if="column.key === 'operation'">
                        <a-button type="link"
                            @click="isUpdate = true; updateFrom = JSON.parse(JSON.stringify(record))">修改</a-button>
                        <a-popconfirm title="不可逆操作，请谨慎执行" ok-text="执行" cancel-text="取消"
                            @confirm="deleteSubmit(record.rcaid)">
                            <a-button type="link" danger>删除</a-button>
                        </a-popconfirm>

                    </template>

                </template>

            </a-table>

        </a-card>

        <!-- 新增弹框 -->
        <a-modal v-model:open="isInsert" ref="insertFormRef" title="新增" :keyboard="false" :maskClosable="false">
            <a-form :model="formState" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }" @finish="insertSubmit"
                @finishFailed="() => message.error('请检查填写是否完整')">

                <a-form-item label="漫画ID" name="cid" :rules="[{ required: true, message: '必填项' }]">
                    <a-select v-model:value="formState.cid" placeholder="请选择漫画ID">
                        <!-- <a-select-option  :value="null">{{ "未选择" }}</a-select-option> -->
                        <a-select-option v-for="e in cartoon" :value="e.cid">
                            {{ e.cid + " : " + e.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="作者ID" name="aid" :rules="[{ required: true, message: '必填项' }]">
                    <a-select v-model:value="formState.aid" placeholder="请选择作者ID">
                        <!-- <a-select-option  :value="null">{{ "未选择" }}</a-select-option> -->
                        <a-select-option v-for="e in authors" :value="e.aid">
                            {{ e.aid + " : " + e.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                    <a-button type="primary" html-type="submit">提交</a-button>
                </a-form-item>

            </a-form>
            <template #footer>
                <a-button @click="isInsert = false">关闭</a-button>
            </template>
        </a-modal>

        <!-- 修改弹框 -->
        <a-modal v-model:open="isUpdate" ref="updateFromRef" title="修改" :keyboard="false" :maskClosable="false">
            <a-form :model="updateFrom" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }" @finish="updateSubmit"
                @finishFailed="() => message.error('请检查填写是否完整')">

                <a-form-item label="ID" name="id">
                    <a-tooltip placement="top" title="唯一键不可修改">
                        <a-input v-model:value="updateFrom.rcaid" disabled />
                    </a-tooltip>
                </a-form-item>

                <a-form-item label="漫画ID" name="cid" :rules="[{ required: true, message: '必填项' }]">
                    <a-select v-model:value="updateFrom.cid" placeholder="请选择漫画ID">
                        <a-select-option v-for="e in cartoon" :value="e.cid">
                            {{ e.cid + " : " + e.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="作者ID" name="aid" :rules="[{ required: true, message: '必填项' }]">
                    <a-select v-model:value="updateFrom.aid" placeholder="请选择作者ID">
                        <a-select-option v-for="e in authors" :value="e.aid">
                            {{ e.aid + " : " + e.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                    <a-button type="primary" html-type="submit" :loading="loading">提交</a-button>
                </a-form-item>

            </a-form>
            <template #footer>
                <a-button @click="isUpdate = false">关闭</a-button>
            </template>
        </a-modal>


    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, h } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { api } from '@/myAxios';
import { HttpStatusCode } from 'axios';


const dataSource = ref([
    {
        "rcaid": -1,
        "cid": -1,
        "aid": -1,
        "createTime": "2024-05-13T08:22:12.000+00:00",
        "updateTime": "2024-05-13T08:22:12.000+00:00",
        "state": -1
    },
])
const cartoon = ref<any>([])
const authors = ref<any>([])

const columns = [
    {
        title: "ID",
        dataIndex: 'rcaid',
        width: 20,
        align: 'center',
    },
    {
        title: "漫画ID",
        dataIndex: 'cid',
        width: 40,
        align: 'center',
    },
    {
        title: "漫画名称",
        width: 120,
        align: 'center',
        foreignKey: {
            key1: 'cid',
            src: cartoon,
            key2: 'name',
        }
    },
    {
        title: "作者ID",
        dataIndex: 'aid',
        width: 40,
        align: 'center',
    },
    {
        title: "作者笔名",
        width: 120,
        align: 'center',
        foreignKey: {
            key1: 'aid',
            src: authors,
            key2: 'name',
        }
    },
    {
        title: "入库时间",
        dataIndex: 'createTime',
        width: 120,
        dataType: 'date',
        resizable: true,
    },
    {
        title: "更新时间",
        dataIndex: 'updateTime',
        width: 120,
        dataType: 'date',
        resizable: true,
    },
    {
        key: 'operation',
        title: "操作",
        fixed: 'right',
        width: 100,
    },
]

const pagination = {
    size: 'large',
    defaultPageSize: 5,
    pageSizeOptions: ['5', '10', '15', '20'],
    showSizeChanger: true,
    showQuickJumper: true,
}

const searchForm = ref({
    cid: null,
    aid: null,
})
const clearSearchForm = () => {
    searchForm.value = {
        cid: null,
        aid: null,
    }
}

const loading = ref(false);

const isInsert = ref(false);
const formState = ref({
    cid: null,
    aid: null,
})


const isUpdate = ref(false);
const updateFrom = ref({
    rcaid: null,
    cid: null,
    aid: null,
})

onMounted(
    () => {
        getDataSource();
        getCartoonList();
        getAuthorList();
    }
)

const getDataSource = async () => {
    loading.value = true;
    try {
        const params = {
            cid: searchForm.value.cid,
            aid: searchForm.value.aid
        }
        const result = await api.get('/relationCartoonAuthor', { params })

        if (result.data.code === HttpStatusCode.Ok) {
            dataSource.value = result.data.data;
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        } else {
            throw new Error(result.data.msg);
        }
    } catch (err) {
        console.log(err);
        message.error('获取信息失败！！');
    } finally {
        loading.value = false;
    }
}

const getCartoonList = async () => {
    try {
        const result = await api.get('/cartoon/list');

        if (result.data.code === HttpStatusCode.Ok) {
            cartoon.value = result.data.data;
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        } else {
            throw new Error(result.data.msg);
        }
    } catch (err) {
        console.log(err);
        message.error('获取信息失败！！');
    }
}

const getAuthorList = async () => {
    try {
        const result = await api.get('/author');

        if (result.data.code === HttpStatusCode.Ok) {
            authors.value = result.data.data;
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        } else {
            throw new Error(result.data.msg);
        }
    } catch (err) {
        console.log(err);
        message.error('获取信息失败!!');
    }
};

const getToForeignKey = (foreignKey: any, record: any) => {
    const src = foreignKey.src.value;
    const key1 = foreignKey.key1;
    const key2 = foreignKey.key2;
    const obj = src.find((obj: any) => obj[key1] === record[key1]);
    const value = obj ? obj[key2] : undefined;

    return '< ' + value + ' >';
};

const insertSubmit = async () => {
    loading.value = true;
    try {
        const data = {
            cid: formState.value.cid,
            aid: formState.value.aid,
        };
        const result = await api.post('/relationCartoonAuthor', data);

        if (result.data.code === HttpStatusCode.Ok) {
            isInsert.value = false;
            console.log(result.data);
            message.success(`新增数据成功：${result.data.data}`);
            getDataSource();
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        } else {
            throw new Error(result.data.msg);
        }
    } catch (err) {
        console.log(err);
        message.error('访问接口失败!!');
    } finally {
        loading.value = false;
    }
};

const updateSubmit = async () => {
    loading.value = true;
    try {
        const data = {
            rcaid: updateFrom.value.rcaid,
            cid: updateFrom.value.cid,
            aid: updateFrom.value.aid,
        };

        const result = await api.put('/relationCartoonAuthor', data);

        if (result.data.code === HttpStatusCode.Ok) {
            isUpdate.value = false;
            getDataSource();
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        } else {
            throw new Error(result.data.msg);
        }
    } catch (err) {
        console.log(err);
        message.error('访问接口失败!!');
    } finally {
        loading.value = false;
    }
};

const deleteSubmit = async (id: number) => {
    try {
        const data = [id];

        const result = await api.delete('/relationCartoonAuthor/' + data);

        if (result.data.code === 200) {
            getDataSource();
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        } else {
            throw new Error(result.data.msg);
        }
    } catch (err) {
        console.log(err);
        message.error('获取信息失败!!');
    }
};


</script>